package com.bootdo.common.interceptor;

import com.bootdo.common.utils.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class I18nInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
       /* String luanguage =getCookieValue(httpServletRequest);
        if(StringUtils.isBlank(luanguage)){
            httpServletRequest.setAttribute("i18n","zh/");
            Cookie c=new Cookie("i18n","zh/");
            c.setPath("/");
            c.setMaxAge(60*60*3);
            httpServletResponse.addCookie(c);
        }else{
            Cookie c=new Cookie("i18n",luanguage);
            c.setPath("/");
            c.setMaxAge(60*60*3);
            httpServletResponse.addCookie(c);
            httpServletRequest.setAttribute("i18n",luanguage);

        }*/

        HttpSession httpSession = httpServletRequest.getSession(false);
        if(null!=httpSession){
            Object language = httpSession.getAttribute("i18n");
            if(null==language||StringUtils.isBlank(language.toString())){
                httpServletRequest.setAttribute("i18n","zh/");
                httpSession.setAttribute("i18n","zh/");
            }else{
                httpServletRequest.setAttribute("i18n",language.toString());
                httpSession.setAttribute("i18n",language.toString());
            }
        }else{
            httpServletRequest.setAttribute("i18n","zh/");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }


    private String getCookieValue(HttpServletRequest httpServletRequest){
        Cookie[] cookies=httpServletRequest.getCookies();
        if(null!=cookies){
            for(Cookie cookie:cookies){
                if("i18n".equalsIgnoreCase(cookie.getName())){
                    return cookie.getValue()==null?"":cookie.getValue().trim();
                }
            }
        }
        return "";
    }
}
